package org.example.company.conponent;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.example.company.config.NacosGatewayProperties;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.concurrent.Executor;

//@Component
//@Configuration
public class DynamicRoutServiceImplNacos implements CommandLineRunner {
    private final DynamicRouteServiceImpl dynamicRouteServiceimpl;
    private final NacosGatewayProperties nacosGatewayProperties;

    public DynamicRoutServiceImplNacos(DynamicRouteServiceImpl dynamicRouteServiceimpl, NacosGatewayProperties nacosGatewayProperties) {
        this.dynamicRouteServiceimpl = dynamicRouteServiceimpl;
        this.nacosGatewayProperties = nacosGatewayProperties;
    }

    //监听nacos service下发的动态路由配置
    public void dynamicRouteByNacosListener(){
        try {
            ConfigService configService = NacosFactory.createConfigService(nacosGatewayProperties.getAddress());
            //程序启动的时候从配置中华读取配置信息
            String config = configService.getConfig(nacosGatewayProperties.getDataID(), nacosGatewayProperties.getGroupId(), nacosGatewayProperties.getTimeout());
            //转化成json
            List<RouteDefinition> routeDefinitions = JSON.parseArray(config, RouteDefinition.class);
            if (!CollectionUtils.isEmpty(routeDefinitions)) {
                dynamicRouteServiceimpl.updateBatch(routeDefinitions);
            }
            //添加配置信息变更监听器
            configService.addListener(nacosGatewayProperties.getDataID(), nacosGatewayProperties.getGroupId(), new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println(configInfo.toString());
                    List<RouteDefinition> definitions = JSON.parseArray(configInfo, RouteDefinition.class);
                    dynamicRouteServiceimpl.updateBatch(definitions);
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run(String... args) throws Exception {
        dynamicRouteByNacosListener();
    }
}
